package com.example.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * List通用排序工具类
 */
public class ListSortUtils {

    private static final String SORT_ASC = "asc";

    private static final String SORT_DESC = "desc";

    /**
     * [简述]： 对List数组排序
     *
     * @param list
     *            源数据 排序集合
     * @param sort
     *            升序 还是 降序，默认升序
     * @return List
     */
    public static List<?> sort(List<?> list, final String sort) {
        Collections.sort(list, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                int ret = 0;
                if (o1 instanceof Integer) {
                    ret = ((Integer) o1).compareTo((Integer) o2);
                } else if (o1 instanceof Double) {
                    ret = ((Double) o1).compareTo((Double) o2);
                } else if (o1 instanceof Long) {
                    ret = ((Long) o1).compareTo((Long) o2);
                } else if (o1 instanceof Float) {
                    ret = ((Float) o1).compareTo((Float) o2);
                } else if (o1 instanceof Date) {
                    ret = ((Date) o1).compareTo((Date) o2);
                } else if (isDouble(String.valueOf(o1))
                        && isDouble(String.valueOf(o2))) {
                    ret = (new Double(o1.toString())).compareTo(new Double(o2
                            .toString()));
                } else {
                    ret = String.valueOf(o1).compareTo(String.valueOf(o2));
                }
                if (null != sort && SORT_DESC.equalsIgnoreCase(sort)) {
                    return -ret;
                } else {
                    return ret;
                }
            }
        });
        return list;
    }


    private static boolean isDouble(String str) {
        boolean flag = false;
        if (isInteger(str) || isFloat(str)) {
            flag = true;
        }
        return flag;
    }

    private static boolean isInteger(String str) {
        Matcher matcher = Pattern.compile("^[+-]?[0-9]+$").matcher(str);
        return matcher.find();
    }

    private static boolean isFloat(String str) {
        return str.matches("[\\d]+\\.[\\d]+");
    }

    private static String getMethodName(String str) {
        StringBuffer name = new StringBuffer();
        name = name.append("get").append(firstLetterToCapture(str));
        return name.toString();
    }

    private static String firstLetterToCapture(String name) {
        char[] arr = name.toCharArray();
        arr[0] -= 32;
        return String.valueOf(arr);
    }

}